package com.easy.service.impl;

import com.easy.bean.Notification;
import com.easy.mapper.NotificationDao;
import com.easy.service.NotificationService;
import com.easy.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class NotificationServiceImpl implements NotificationService {

    private static final String CACHE_NAME = "notification";

    @Autowired
    NotificationDao notificationDao;

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'notification:' + #p0.id", condition = "#result != null")
    public Notification add(Notification notification) {
        notificationDao.add(notification);
        return notificationDao.one(notification.getId());
    }

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'notification:id:' + #p0")
    public int del(Integer id) {
        return notificationDao.del(id);
    }

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'notification:' + #p0.id", condition = "#p0 != null and #p0.id != null")
    public Notification edit(Notification notification) {
        notificationDao.edit(notification);
        return notificationDao.one(notification.getId());
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'notification:list:' + T(java.util.Objects).hash(#p0)", unless = "#result == null or #result.isEmpty()")
    public List<Notification> all(Notification notification) {
        return notificationDao.all(notification);
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'notification:id:' + #p0", unless = "#result == null")
    public Notification one(Integer id) {
        return notificationDao.one(id);
    }

    @Override
    public void page(Page page, Notification notification) {
        int count = notificationDao.pageCount(notification);
        Object data = notificationDao.page(page, notification);
        page.setCount(count);
        page.setData(data);
    }

    @Override
    public void pageWithDetails(Page page, Notification notification) {
        int count = notificationDao.pageCountWithDetails(notification);
        Object data = notificationDao.pageWithDetails(page, notification);
        page.setCount(count);
        page.setData(data);
    }
}
